<?php
namespace app\admin\controller;
use think\Controller;
// use app\api\Controller\Common;
use think\Db;
use think\Cache;
use think\Image;
use think\Session;
use app\api\model\PrivatechatDeleTask;
use app\service\BaiduApi;
class Usertalk extends Common
{
    public function index()
    {
        $data=DB::name('privatechat t')->join('user m','t.userid=m.id')->where('t.k',1)->group('m.id')->field('m.name,m.head_portrait,t.*')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function($item, $key){
            $item['wei'] =DB::name('privatechat')->where(['userid'=>$item['userid'],'k'=>1,'isRead'=>0])->count();
            $item['newmsg'] =DB::name('privatechat')->where(['userid'=>$item['userid'],'k'=>1])->order('id desc')->find();
            return $item;
        });
        $this->assign('data',$data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }
    public function nvshen()
    {
        $touid=input('touid/d');
        if (!$touid) {
            $this->error('缺少参数');
        }
        $data=DB::name('privatechat t')->join('user m','t.userid=m.id')->where('k',1)->where('t.userid',$touid)->group('m.id')->field('m.head_portrait,m.name,t.*')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function($item, $key){
            $item['wei'] =DB::name('privatechat')->where('k',1)->where(['userid'=>$item['userid'],'isRead'=>0,'uid'=>$item['uid']])->count();
            $item['newmsg'] =DB::name('usertalk')->where(['userid'=>$item['userid']])->order('id desc')->find();
            return $item;
        });
        // var_dump($data);exit;
        $this->assign('data',$data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }
    // 回复界面
    public function huifu()
    {
        $touid=input('touid/d');
        $id=[];
        if (!$touid) {
            $this->success('缺少参数','index/off');
        }
        $limit=20;
        $page=1;
        $data=DB::name('privatechat')->where(function ($query)use($touid) {
            $query->where('userid',$touid)->where('k',1);
        })->whereOR(function ($query)use($touid) {
            $query->where('touserid',$touid)->where('k',1);
        })->order('id desc,addtime desc')->limit($limit)->select();
        // var_dump($data);exit;
        $count=DB::name('privatechat')->where(function ($query)use($touid) {
            $query->where('userid',$touid)->where('k',1);
        })->whereOR(function ($query)use($touid) {
            $query->where('touserid',$touid)->where('k',1);
        })->limit($limit)->count();
        $data=array_reverse($data);
        $user=DB::name('user')->where('id',$touid)->find();
        if (!$user) {
            $this->success('当前用户不存在','index/off');
        }
        if ($user['head_portrait']) {
            $user['head_portrait']=checkpath(_imgUrl('1').$user['head_portrait']);
        }
        foreach ($data as $k => $v) {
            if ($v['type']===0) {
                $data[$k]['content']=biaoqing($v['content']);
            }
            if ($v['type']==1) {
                $data[$k]['image']=checkpath(_imgUrl('3').$v['content']);
            }
            if ($v['type']==2) {
                if (file_exists('apis/'.$data[$k]['content'])) {
                    $a=file_get_contents('apis/'.$data[$k]['content']);
                    $b=base64_encode($a);
                    $data[$k]['content']=$b;
                }
            }
            if ($v['userid']==$touid) {
                $id[]=$v['id'];
            }

        }
        //标记为已读
        if ($id) {
            DB::name('privatechat')->where('id','in',$id)->update(['isRead'=>1]);
        }
        $this->assign('count',$count);
        $this->assign('page',$page);
        $this->assign('limit',$limit);
        $this->assign('data',$data);
        $this->assign('touid',$touid);
        $this->assign('user',$user);
        return $this->fetch();
    }
    //获取上一页记录
    public function shang()
    {
        $uid=input('uid/d');
        $touid=input('touid/d');
        $first=input('first/d');
        //$touid=10;
        //$first=82;
        $id=[];
        $type=input('type');
        if ($type) {
            $yu='<';
        }else{
            $yu='>';
        }
        if (!$first||!$touid) {
            $this->error('缺少参数');
        }
        $limit=20;
        $id=[];
        if (!$type) {
            $weidu=DB::name('privatechat')->where(['userid'=>$touid,'isRead'=>0])->count();
        }else{
            $weidu=0;
        }

        $data=DB::name('privatechat')->where(function ($query)use($touid,$yu,$first) {
            $query->where('userid',$touid)->where('id',$yu,$first);
        })->whereOR(function ($query)use($touid,$yu,$first) {
            $query->where('touserid',$touid)->where('id',$yu,$first);
        })->order('id desc')->limit($limit)->select();

        $count=DB::name('privatechat')->where(function ($query)use($touid,$yu,$first) {
            $query->where('userid',$touid)->where('id',$yu,$first);
        })->whereOR(function ($query)use($touid,$yu,$first) {
            $query->where('touserid',$touid)->where('id',$yu,$first);
        })->count();
        $data=array_reverse($data);
        foreach ($data as $k => $v) {
            if ($v['type']===0) {
                $data[$k]['content']=biaoqing($v['content']);
            }
            if ($v['type']==1) {
                $data[$k]['image']=$v['content'];
            }
            if ($v['type']==2) {
                if (file_exists('apis/'.$data[$k]['content'])) {
                    $a=file_get_contents('apis/'.$data[$k]['content']);
                    $b=base64_encode($a);
                    $data[$k]['content']=$b;
                }
            }
            if ($v['userid']==$touid) {
                $id[]=$v['id'];
            }
        }
        //标记为已读
        if ($id) {
            //db('privatechat')->where('id','in',$id)->update(['isRead'=>1]);
        }

        $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '/apis/index.php/home/privatechat/';
        $re = curl(str_replace('/index.php/apis', '/apis',$url) . 'changeread', json_encode(['user_id' => $uid, 'touserid' => $touid]));

        return ['code'=>200,'data'=>$data,'total'=>$count,'weidu'=>$weidu];
    }

    //刷新聊天页面
    // public function ajaxchat(){
    //     $touid =input('touid/d');
    //     $uid = input('uid/d');
    //     $limit=20;

    //     $weidu=db('privatechat')->where(['uid'=>$uid,'touid'=>$touid,'isRead'=>0])->order('id desc,addtime desc')->count();

    //     $data=db('privatechat')->where(['uid'=>[['=',$uid],['=',$touid],'or'],'touid'=>[['=',$uid],['=',$touid],'or']])->order('id desc,addtime desc')->limit($limit)->select();
    //     $id=[];
    //     foreach ($data as $k => $v) {
    //         if ($v['type']=='1') {
    //             $data[$k]['image']=checkpath(_imgUrl('1').$v['image']);
    //         }
    //         if ($v['touid']==$touid) {
    //            $id[]=$v['id'];
    //         }

    //     }
    //     //标记为已读
    //     if ($id) {
    //         db('privatechat')->where('id','in',$id)->update(['isRead'=>1]);
    //     }
    //     $data=array_reverse($data);
    //     return ['weidu'=>$weidu,'data'=>$data];
    // }

    //获取最新的20条信息
    public function getMsgList(){

        $uid = input('uid');
        $touid = input('touid');
        if (!$uid||!$touid) {
            $returnArr=['code'=>400,'msg'=>'请输入用户id'];
            echo json_encode($returnArr);
            exit();
        }
        $page = input('page')?input('page'):1;
        $count =db('usertalk t')->where('t.uid',['=',$uid],['=',$touid],'or')->where('t.touid',['=',$uid],['=',$touid],'or')->count();
        // var_dump($count);
        $lastTime = "";
        $result=db('usertalk t')->field('t1.img,t1.nickname,t.*')->join('member t1','t1.id=t.uid')->where('t.uid',['=',$uid],['=',$touid],'or')->where('t.touid',['=',$uid],['=',$touid],'or')->order('t.addtime')->limit(20*($page-1),20)->select();
        // ->where('t.uid',['=',$uid],['=',$touid],'or')
        // var_dump($result);exit;
        foreach ($result as $k => $v) {
            $isRead = $v['isRead'];
            if($isRead == 0&&$uid==$v['touid']){
                $updateArr = array(
                    "isRead"=>1
                );
                db('usertalk')->where('id',$v['id'])->update($updateArr);

            }
            if($uid == $v['uid']){
                $v['self'] = 1;
            }else{
                $v['self'] = 0;
            }

            $v['showtime'] = false;
            $second=floor(time()-strtotime($v['addtime']));
            // $result[$k]['addtime'] = $second;
            if($second>300){
                $result[$k]['showtime'] = true;
            }else{
                $result[$k]['showtime'] = false;
            }
            $result[$k]['time'] = _time(strtotime($v['addtime']));
        }
        $returnArr = array(
            "code"=>200,
            "data"=>$result,
            'per_page'=>$page,
            'total'=>$count,
            'current_page'=>20
        );
        echo json_encode($returnArr);
        exit();
    }

    //添加用户聊天信息
    public function addTalk(){
        $userid = input('userid');
        $touserid = input('touserid');
        $type = input('type')?input('type'):0;
        $second = input('second');
        $content = input('content');

        if (!in_array($type, ['0','1','2'])) {
            exit(json_encode(['code'=>400,'msg'=>'插入失败']));
        }
        if($type == 0){
            $insertArr = array(
                "userid"=>$userid,
                "touserid"=>$touserid,
                "type"=>0,
                //"k"=>1,
                "content"=>$content
            );


        }else if($type == 1){
            $insertArr = array(
                "userid"=>$userid,
                "touserid"=>$touserid,
                "type"=>$type,
                "content"=>$content,
            );
            /*$file = request()->file("file");
            $image = Image::open($file);
            $info = $file->validate(['size'=>10567800,'ext'=>'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'sixin' . DS . 'images');
            if($info){

                $img='public/uploads/sixin/images/'.$info->getSaveName();
                $img=str_replace('\\','/',$img);

                // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                $image->thumb(2000, 2000)->save($img);

                $insertArr = array(
                    "userid"=>$userid,
                    "touserid"=>$touserid,
                    "type"=>$type,
                    "k"=>1,
                    "content"=>$img,
                    "image"=>$img
                );
            }else{
                echo json_encode(['err'=>$file->getError()]);exit;
            }*/
            // if ($_FILES) {
            //     $UpFileTool = new \Think\UpFileTool('file');// 实例化上传类

            //     $UpFileTool->upImage(0.3,'Uploads','Uploads');
            //     $images=$UpFileTool->srcImage;
            //     $sumbimages = $UpFileTool->sumbImage;


            // }
        }else if($type == 2){
            // if($_FILES){
            //     $UpFileTool = new \Think\UpFileTool('file');

            //     $UpFileTool->upFile($srcimage='Uploads');
            //     $sound=$UpFileTool->srcImage;

            //     $insertArr = array(
            //         "userid"=>$userid,
            //         "touserid"=>$touserid,
            //         "type"=>$type,
            //         "content"=>$sound,
            //         "second"=>$second
            //     );
            // }
            $file = request()->file("file");

            $info = $file->validate(['size'=>10567800,'ext'=>'amr'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'weitoutiao' . DS . 'sound');
            if($info){

                $sound='public/uploads/weitoutiao/sound/'.$info->getSaveName();
                $sound=str_replace('\\','/',$sound);
                $insertArr = array(
                    "userid"=>$userid,
                    "touserid"=>$touserid,
                    "type"=>$type,
                    "content"=>$sound,
                    "second"=>$second,
                    "k"=>1
                );
            }else{
                echo json_encode(['err'=>$file->getError()]);exit;
            }
        }
        $res=db('privatechat')->insertGetId($insertArr);
        if($res){
            exit(json_encode(['code'=>200,'msg'=>'插入成功','id'=>$res]));

        }else{
            exit(json_encode(['code'=>400,'msg'=>'插入失败']));
        }
    }

    //获取用户消息
    public function getMyMsgList(){
        $userid = input('uid');
        // $result = $Model->Query("SELECT t.touserid,t.content,t1.sumb_headimg,t1.name FROM usertalk t,USER t1 WHERE t.touserid=".$userid." or t.userid=".$userid." AND t.touserid=t1.user_id ORDER BY t.addtime desc LIMIT 0,1");
        $result =db('usertalk t')->field('t.touid,t.content,t1.img,t1.nickname')->join('member t1','t.touid=t1.id')->where([['t.touid'=>$userid],['t.uid'=>$userid],'or'])->order('t.addtime')->limit(0,1)->select();
        // $result = array($result);
        echo json_encode(['code'=>200,'data'=>$result]);exit;
        // echo getSuccessJson($result);
    }

    //获取信息列表
    public function getOtherList(){
        $userid = input('uid');
        // $result = $Model->Query("(SELECT userid,MAX(id) AS id FROM usertalk WHERE touserid=".$userid."  GROUP BY userid) UNION (SELECT touserid,MAX(id) AS id FROM usertalk WHERE userid=".$userid."  GROUP BY touserid)");
        $result1=db('usertalk')->field('uid,MAX(id)')->where('uid',$userid)->group('uid')->select();
        $result2=db('usertalk')->field('touid,MAX(id)')->where('uid',$userid)->group('touid')->select();
        $result=array_merge($result1,$result2);
        $result = assoc_unique($result,'uid');
        foreach ($result as $k => $v) {
            $usertalk =db('usertalk')->where('id',$result[$k]['id'])->find();
            $usertalk['addtime'] = _time(strtotime($usertalk['addtime']));
            // $user = $Model->Query("select * from user where user_id=".$result[$i]['userid']."");
            $user=db('member')->where('id',$result[$k]['uid'])->find();
            $count =db('usertalk')->where(['uid'=>$usertalk['uid'],'touid'=>$usertalk['touid']])->whereOr(['uid'=>$usertalk['touid'],'touid'=>$usertalk['uid']])->where('isRead',0)->count();
            // $count = $Model->Query("SELECT COUNT(*) AS count FROM usertalk WHERE ((userid=".$usertalk[0]['userid']." AND touserid=".$usertalk[0]['touserid'].") OR (userid=".$usertalk[0]['touserid']." AND touserid=".$usertalk[0]['userid'].")) AND touserid=".$userid." and isRead=0");
            $result[$k]['content'] = $usertalk['content'];
            $result[$k]['touid'] = $result[$k]['uid'];
            $result[$k]['addtime'] = $usertalk['addtime'];
            $result[$k]['isRead'] = $usertalk['isRead'];
            $result[$k]['name'] = $user['nickname'];
            // $result[$k]['sumbheadimg'] = $user['sumbheadimg'];
            $result[$k]['count'] = $count;


            $arr = array("png","jpg","jpeg","gif");
            $lastfix=substr($result[$k]['content1'],strrpos($result[$k]['content1'],'.'));
            //获取文件的后缀名
            if(in_array(trim(strtolower($lastfix),'.'),$arr)){
                $result[$k]['content1'] .= "[图片]".$lastfix;
                $result[$k]['content'] .= "[图片]";
            }

            $arr = array("amr");
            $lastfix=substr($result[$k]['content1'],strrpos($result[$k]['content1'],'.'));

            //获取文件的后缀名
            if(in_array(trim(strtolower($lastfix),'.'),$arr)){
                $result[$k]['content1'] .= "[语音]".$lastfix;
                $result[$k]['content'] .= "[语音]";
            }

        }




        // for($i=0;$i<sizeof($result);$i++){

        json_encode(['code'=>200,'data'=>$result]);exit;

        // }
        $result = array($result);
        echo getSuccessJson($result);
    }

    //获取所有未读私信
    public function getunread()
    {
        $userid = input('uid');
        // var_dump($userid);exit;
        $result =db('usertalk t')->field('t.uid,t.touid,t1.img,t1.nickname,count(t.id) count')->join('member t1','t.uid=t1.id')->group('t.uid')->where(['t.touid'=>$userid])->order('t.addtime')->select();
        // var_dump($result);exit;
        echo json_encode(['code'=>200,'data'=>$result]);exit;
    }


    public function records()
    {
        //return '暂不开放';
        $where = [];
        $whereor = [];

        //$where['k'] = ['neq', 2];
        //$whereor['k'] = ['neq', 2];

        $type = input('type', 2);
        $d = input('d', 0);
        $types = input('types');
        $start = input('start');
        $end = input('end');
        $kefu = Db::name('config_system')->where(['category'=>'kefu','title'=>'id'])->value('content');
        $whereStr = '';

        if($type == 1){
            $where['addtime'] = ['egt',date('Y-m-d')." 00:00:00"];
        }else if($type == 2){
            // $where['is_identity_authentication'] = '2';

        }else if($type == 3){
            // $where['register_datetime'] = ['egt',date('Y-m-d')];
        }else if($type == 4){
            // $where['sex'] = "男";
            $where['content'] = ['EXP', Db::raw('not like "您围观的Flag%" and content not like "恭喜！本次转盘抽奖你抽中了%" and content not like "您发布的合集%"')];
        }else if($type == 6){
            $where['single'] = 1;
        }else if($type == 7){
            $where['single'] = 2;
        }else if($type == 8){
            $whereStr = "(is_fate=0 and front_id!='') or (type in (9,10))";
            $where['userid'] = ['<>', $kefu];
            $where['touserid'] = ['<>', $kefu];
            $where['type'] = ['>=', -1];
        }

        $searchname=$search_name=input('param.name');
        $search_type=input('param.search');

        if (in_array($type, [-1,6,7,8]) || $types || ($searchname&&!in_array($search_type, ['userid','touserid','id']))) {
            if (!$start) {
                $start = date('Y-m-d', strtotime('-3 day')) . ' 00:00:00';
            }
        }

        if($search_name && $search_type !== null){
            if (stripos($search_name, ',') && $search_type == 'userid') {
                $search_name = explode(',', $search_name);
                $where['userid']  = $search_name[0];
                $where['touserid']  = $search_name[1];
                $whereor['touserid']  = $search_name[0];
                $whereor['userid']  = $search_name[1];
                if($types){
                    $where['type']  = $types == 3 ? 1 : $types;
                    $whereor['type']  = $types == 3 ? 1 : $types;
                    if ($where['type']==1) {
                        unset($where['type'], $whereor['type']);
                        $where['content'] = ['like', '%/disk/uploads/image/%'];
                        $whereor['content'] = ['like', '%/disk/uploads/image/%'];
                    }
                    if ($types == 3) {
                        $whereor['is_fate'] = 1;
                    } else if ($types == 6) {
                        $where['type'] = ['in', [9,10]];
                    } else if ($types == 5) {
                        $where['type'] = -1;
                        $where['status'] = 3;
                        $where['content'] = ['<>', '对方查看了你的消息'];
                        $where['single'] = ['<>', 1];
                        $whereor['type'] = -1;
                        $whereor['status'] = 3;
                        $whereor['content'] = ['<>', '对方查看了你的消息'];
                        $whereor['single'] = ['<>', 1];
                    }
                }
            } else if($search_type == 'userid') {
                $where['userid']  = $search_name;
                $whereor['touserid']  = $search_name;
                if($types){
                    $where['type']  = $types == 3 ? 1 : $types;
                    $whereor['type']  = $types == 3 ? 1 : $types;
                    if ($where['type']==1) {
                        unset($where['type'], $whereor['type']);
                        $where['content'] = ['like', '%/disk/uploads/image/%'];
                        $whereor['content'] = ['like', '%/disk/uploads/image/%'];
                    }
                    if ($types == 3) {
                        $whereor['is_fate'] = 1;
                    } else if ($types == 6) {
                        $where['type'] = ['in', [9,10]];
                    } else if ($types == 5) {
                        $where['type'] = -1;
                        $where['status'] = 3;
                        $where['content'] = ['<>', '对方查看了你的消息'];
                        $where['single'] = ['<>', 1];
                        $whereor['type'] = -1;
                        $whereor['status'] = 3;
                        $whereor['content'] = ['<>', '对方查看了你的消息'];
                        $whereor['single'] = ['<>', 1];
                    }
                }
            } else if($search_type == 'touserid') {
                $where['touserid']  = $search_name;
                if($types){
                    $where['type']  = $types == 3 ? 1 : $types;
                    if ($where['type']==1) {
                        unset($where['type'], $whereor['type']);
                        $where['content'] = ['like', '%/disk/uploads/image/%'];
                    }
                    if ($types == 3) {
                    } else if ($types == 6) {
                        $where['type'] = ['in', [9,10]];
                    } else if ($types == 5) {
                        $where['type'] = -1;
                        $where['status'] = 3;
                        $where['content'] = ['<>', '对方查看了你的消息'];
                        $where['single'] = ['<>', 1];
                    }
                }
            } else if($search_type == 'id') {
                $where[$search_type] = $whereor[$search_type] = $search_name;
            } else {
                // $where['type'] = $whereor['type'] = 0;
                $where[$search_type] = $whereor[$search_type] = ['like', "%$search_name%"];
                if($types){
                    $where['type']  = $types == 3 ? 1 : $types;
                    if ($where['type'] == 1) {
                        $whereor['content'] = ['like', '%/disk/uploads/image/%'];
                    }
                }
            }
        } else {
            if($type == 3){
                $ids = Db::name('user')->where(['role' => 1])->column('id');
                if ($ids) {
                    $where['userid']  = ['in', $ids];
                    $whereor['touserid']  = ['in', $ids];

                    $this->assign('ids',$ids);
                } else {
                    $where['userid']  = -1;
                    $this->assign('ids',[]);
                }
            }

            if($types){
                $where['type']  = $types == 3 ? 1 : $types;
                if ($where['type'] == 1) {
                    $whereor['content'] = ['like', '%/disk/uploads/image/%'];
                }

                if ($types == 5) {
                    $where['type'] = -1;
                    $where['status'] = 3;
                    $where['content'] = ['<>', '对方查看了你的消息'];
                    $where['single'] = ['<>', 1];
                    $whereor['type'] = -1;
                    $whereor['status'] = 3;
                    $whereor['content'] = ['<>', '对方查看了你的消息'];
                    $whereor['single'] = ['<>', 1];
                } else if ($types == 6) {
                    $where['type'] = ['in', [9,10]];
                } 
            }
        }
        if ($types == 3) {
            $where['is_fate'] = 1;
        }else if($types == 4){
            $where['type'] = 0;
            // $where['content'] = Db::raw("REGEXP '^[A-Za-z0-9]+$' or content like '%一%' or content like '%二%' or content like '%三%' or content like '%四%' or content like '%五%' or content like '%六%' or content like '%七%' or content like '%八%' or content like '%九%'");
            $where['content'] = Db::raw("REGEXP '[A-Za-z0-9]'");
            $where['userid'] = ['<>', $kefu];
            $where['touserid'] = ['<>', $kefu];
        }


        if (!isset($where['id'])) {
            if ($start && $end) {
                $where['addtime'] = $whereor['addtime'] = ['between', [$start, $end]];
                $start_id = _day_first_id($start);
                $end_id = _day_first_id(date('Y-m-d', strtotime($start))==date('Y-m-d', strtotime($end))?date('Y-m-d', strtotime($end)+86400):$end, $start_id);
                if ($end_id) {
                    $where['id'] = $whereor['id'] = ['between', [$start_id, $end_id]];
                }
            } else if ($start && !$end) {
                if (time() - strtotime($start) > 6 * 60*60*24*30) {
                    $start = date('Y-m-d') . ' 00:00:00';
                }
                $where['addtime'] = $whereor['addtime'] = ['egt', $start];
                $start_id = _day_first_id($start);
                if ($start_id) {
                    $where['id'] = $whereor['id'] = ['egt', $start_id];
                }
            } else if (!$start && $end) {
                $where['addtime'] = $whereor['addtime'] = ['elt', $end];
                $end_id = _day_first_id($end);
                if ($end_id) {
                    $where['id'] = $whereor['id'] = ['egt', $end_id];
                }
            }else{
                $tenDaysAgo = date('Y-m-d H:i:s', strtotime('-10 days'));
                $where['addtime'] = ['egt', $tenDaysAgo];
            }
        }
        if(in_array($types, [2,4,6]) || in_array($type, [6, 7, 8]) || $search_type == 'touserid'){
            $whereor = [];
        }

        if (in_array($type, [2,6,7])) {
            if(is_array($search_name) || $search_type != 'userid') {

                // $data = Db::name('privatechat')->where($where)->whereOr(function ($query) use ($whereor) {
                //     $query->where($whereor);
                // })->order('id desc')->fetchSql(true)->select();
                // echo($data);exit;

                $data = Db::name('privatechat')->where($where)->whereOr(function ($query) use ($whereor) {
                    $query->where($whereor);
                })->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
                {
                    if ($item['type'] == 1) {
                        $item['content'] = implode('_thumb.', explode('.', $item['content']));
                    }
                    return $item;
                });
            } else {

                $data = Db::name('privatechat')->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
                {
                    if ($item['type'] == 1) {
                        $item['content'] = implode('_thumb.', explode('.', $item['content']));
                    }
                    return $item;
                });
            }
        } elseif($type == 4) {
            // 男用户与客服的记录
            // 避免全表扫描
            $kfid = Db::name('config_system')->where(['title'=>'id'])->cache(60)->value('content');
            $chats = Db::name('privatechat')->where(['userid|touserid'=>$kfid])->field('id,userid,touserid')->select();
            $chatids = implode(',',array_column($chats, 'id'));
            $uidsa = array_column($chats, 'userid');
            $uidsb = array_column($chats, 'touserid');
            $uids = array_unique(array_merge($uidsa, $uidsb));
            $uids = Db::name('user')->where(['sex'=>'男', 'id'=>['in', $uids]])->cache(60)->column('id');
            $uids = implode(',',$uids);
            $where['id'] = ['in', $chatids];
            $where['userid'] = $kfid;
            $where['touserid']  = ['in', $uids];
            $whereor['id'] = ['in', $chatids];
            $whereor['userid']  = ['in', $uids];
            $whereor['touserid'] = $kfid;
            
            if(!$start && !$end){
                $tenDaysAgo = date('Y-m-d H:i:s', strtotime('-10 days'));
                $where1['addtime'] = ['egt', $tenDaysAgo];
            }

            //$whereStr = "id in ($chatids) and ((userid=$kfid and touserid in ($uids)) or (touserid=$kfid and userid in ($uids))) and content not like '您围观的Flag%' and content not like '恭喜！本次转盘抽奖你抽中了%' and content not like '您发布的合集%'";
            $data = Db::name('privatechat')->where($where1)->where($whereStr)->order('id desc')->fetchSql(false)->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
                {
                    if ($item['type'] == 1) {
                        $item['content'] = implode('_thumb.', explode('.', $item['content']));
                    }
                    return $item;
                });
        } elseif($type == -1) {
            $data = Db::name('privatechat')->field('*, max(id) id')->where($where)->whereOr(function ($query) use ($whereor) {
                $query->where($whereor);
            })->order('id desc')->group('userid,touserid')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
                {
                    if ($item['type'] == 1) {
                        $item['content'] = implode('_thumb.', explode('.', $item['content']));
                    }
                    return $item;
                });
        } else if ($type == 5) {
            if(is_array($search_name) || $search_type != 'userid') {

                $data = Db::name('privatechat')->alias('t')->join('user u','(u.id=t.userid or u.id=t.touserid) and u.role=1')->field('t.*')->where($where)->whereOr(function ($query) use ($whereor) {
                    $query->where($whereor);
                })->order('t.id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
                {
                    if ($item['type'] == 1) {
                        $item['content'] = implode('_thumb.', explode('.', $item['content']));
                    }
                    return $item;
                });
            } else {

                $data = Db::name('privatechat')->alias('t')->join('user u','(u.id=t.userid or u.id=t.touserid) and u.role=1')->field('t.*')->where($where)->order('t.id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
                {
                    if ($item['type'] == 1) {
                        $item['content'] = implode('_thumb.', explode('.', $item['content']));
                    }
                    return $item;
                });
            }
        } else if ($type == 8) {
            $data = Db::name('privatechat')->where($where)->where($whereStr)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
            {
                if ($item['type'] == 1) {
                    $item['content'] = implode('_thumb.', explode('.', $item['content']));
                }
                return $item;
            });
        }

        $dataList = $data->all();
        foreach ($dataList as &$value) {
            if ($value['type'] == 2) {
                if (file_exists('apis/' . $value['content'])) {
                    $a = file_get_contents('apis/' . $value['content']);
                    $b = base64_encode($a);
                    $value['content'] = $b;
                }
                if (!$value['front_id']) {
                    $value['is_fate'] = 1;
                    continue;
                }
                $has = Db::name('privatechat_greet')->where(['channel'=>1,'user_id'=>$value['userid'], 'content'=>$value['content']])->cache(86400)->find();
                $value['is_fate'] = $has?1:0;
            }

        }
        
        $admin = Session::get('admin', 'mmjtAdmin');
        $atypeid=$admin['type'];
        //echo $atypeid;
        if($atypeid==7 && !$search_name){//法律顾问 不检索不显示变动金额
            $dataList=array();
            $this->assign('data', $dataList);
            $page='';
            $this->assign('page', $page);
        }else{
            $this->assign('data', $dataList);
            $page = $data->render();
            $this->assign('page', $page);
        }
        
        $this->assign('d',$d);
        $this->assign('type',$type);
        $this->assign('types',$types);
        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('search_type', $search_type);
        $this->assign('search_name', $searchname);

        $this->assign('kefu', $kefu);

        return $this->fetch();
    }
    public function grouprecords()
    {
        $where = [];
        $search_name=input('param.name');
        $search_type=input('param.search');
        $content=input('param.content');

        if ($search_type == 'id') {
            $where['id']  = ['in',$search_name];
            $data = Db::name('privatechat')->master()->field('*')->where($where)->order('id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
            {
                return $item;
            });
        } else{
            $where['userid']  = $search_name;
            $where['type']  = 0;
            $where['content']  = ['like', "%$content%"];
            $data = Db::name('privatechat')->master()->field('*, max(id) id')->where($where)->order('id desc')->group('touserid')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function ($item)
            {
                if ($item['type'] == 1) {
                    $item['content'] = implode('_thumb.', explode('.', $item['content']));
                }
                return $item;
            });
        }


        $this->assign('data',$data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }
    //删除聊天记录
    public function pdel()
    {
        if(request()->isAjax()){
            $id=input('id');

            if($id){
                $result=Db::name('privatechat')->find($id);
                $last = Db::name('privatechat')->where(['userid'=>$result['userid'], 'touserid'=>$result['touserid']])->order('id desc')->find();
                $is_last = $id == $last['id'];
                $db = Db::name('privatechat')->delete($id);
                if ($result['data']) {
                    $json_data = json_decode($result['data'], true);
                    if (isset($json_data['MsgKey'])) {
                        (new \app\service\TencentIM)->delete_c2c_msg_ramble($result['userid'], $result['touserid'], [$json_data['MsgKey']]);
                        (new \app\service\TencentIM)->delete_c2c_msg_ramble($result['touserid'], $result['userid'], [$json_data['MsgKey']]);
                    }
                }
                Db::name('privatechat_dele_task')->insert(['userid'=>$result['userid'], 'touserid'=>$result['touserid'], 'msg_ids'=>$id, 'create_time'=>time()]);
                Db::name('privatechat_dele_task')->insert(['touserid'=>$result['userid'], 'userid'=>$result['touserid'], 'msg_ids'=>$id, 'create_time'=>time()]);
                if($db){
                    if ($is_last) {
                        $lastMsg = Db::name('privatechat')
                                    ->master()
                                    ->where('(userid='.$result['userid'].' and touserid='.$result['touserid'].') or (userid='.$result['touserid'].' and touserid='.$result['userid'].')')
                                    ->where(['single'=>0, 'type'=>['>=',0]])
                                    ->order('id desc')
                                    ->find();
                        $chatListWhere = $result['userid'] < $result['touserid'] ? [
                            'user_id'=>$result['userid'],
                            'another_id'=>$result['touserid']
                        ] : [
                            'user_id'=>$result['touserid'],
                            'another_id'=>$result['userid']
                        ];
                        $addtime = 0;
                        $content = '';
                        $user_unread = 0;
                        $another_unread = 0;
                        if ($lastMsg) {
                            $addtime = strtotime($lastMsg['addtime']);
                            $content = _msgtype($lastMsg['content'],$lastMsg['type']);
                        }
                        if ($result['isRead'] == 0) {
                            if ($result['userid'] == $chatListWhere['user_id']) {
                                $another_unread = 1;
                            } else {
                                $user_unread = 1;
                            }
                        }
                        $chatList = Db::name('chat_lists')->master()->where($chatListWhere)->find();
                        Db::name('chat_lists')->where($chatListWhere)->update([
                            'user_content'=>$content,
                            'another_content'=>$content,
                            'user_channel'=>$lastMsg['type']??0,
                            'another_channel'=>$lastMsg['type']??0,
                            'user_time'=>$addtime,
                            'another_time'=>$addtime,
                            'user_unread'=>$chatList['user_unread']?Db::raw('user_unread-'.$user_unread):0,
                            'another_unread'=>$chatList['another_unread']?Db::raw('another_unread-'.$another_unread):0,
                        ]);
                        // $request = request();
                        // $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getOtherList';
                        // $datas = json_encode(['userid' => $result['touserid']], JSON_UNESCAPED_UNICODE);
                        // sendcurl($url, $datas, 0);
                        // $datas = json_encode(['userid' => $result['userid']], JSON_UNESCAPED_UNICODE);
                        // sendcurl($url, $datas, 0);
                    }
                    $users = Db::name('user')->where(['id'=>['in', [$result['userid'],$result['touserid']]]])->field('id,reg,authcode')->select();
                    foreach ($users as $uk => $uv) {
                        PrivatechatDeleTask::pushtask($uv['id'], $uv['reg'] == 2 ? $uv['authcode'] : $uv['id']);
                    }
                    if ($result['type'] == 2) {
                        $hifile = Db::name('privatechat_greet')->where(['content'=>$result['content']])->find();
                        if (!$hifile) {
                            \app\service\AliOss::delete($result['content']);
                        }
                    } else if(in_array($result['type'], [1,3,4])){
                        \app\service\AliOss::delete($result['content']);
                    }
                    $data=['ret'=>'删除成功'];
                }else{
                    $data=['err'=>'删除失败'];
                }
            }else{
                $data=['err'=>'id参数错误'];
            }
        }else{
            $data=['err'=>'提交参数错误'];
        }
        return $data;
    }
    public function delalls()
    {
        if(request()->isAjax()){
            $id=input('id');
            $reset=input('reset', 0);
            if($id){
                $result=Db::name('privatechat')->find($id);
                // $db=Db::name('privatechat')->delete($id);
                $last = Db::query("(select * from privatechat where userid=".$result['userid']." and touserid=".$result['touserid'].") union (select * from privatechat where userid=".$result['touserid']." and touserid=".$result['userid'].") order by id desc");


                $ids = array_column($last, 'id');
                $idstrs = implode(',', $ids);
                // var_dump($last);exit;
                $last_id = $last[0]['id'];
                $files = [];
                Db::query("delete from privatechat where id in ($idstrs)");
                $db = Db::name('privatechat_dele_task')->insert(['userid'=>$result['userid'], 'touserid'=>$result['touserid'], 'last_id'=>$last_id,  'create_time'=>time()]);
                $db = Db::name('privatechat_dele_task')->insert(['userid'=>$result['touserid'], 'touserid'=>$result['userid'], 'last_id'=>$last_id,  'create_time'=>time()]);
                $where = $result['userid'] > $result['touserid'] ? ['user_id'=>$result['touserid'], 'another_id'=>$result['userid']] : ['user_id'=>$result['userid'], 'another_id'=>$result['touserid']];
                if ($reset) {
                    Db::name('chat_lists')->where($where)->delete();
                    Db::name('chat_charge_records')->where($where)->delete();
                } else {
                    Db::name('chat_lists')->where($where)->update(['user_content'=>'','another_content'=>'','user_unread'=>0,'another_unread'=>0,'user_time'=>0,'another_time'=>0]);
                }


                $cloudList = true;
                while ($cloudList) {
                    $list = (new \app\service\TencentIM)->admin_getroammsg($result['userid'], $result['touserid'], 30);
                    if (isset($list['MsgList']) && sizeof($list['MsgList'])) {
                        (new \app\service\TencentIM)->delete_c2c_msg_ramble($result['userid'], $result['touserid'], array_column($list['MsgList'], 'MsgKey'));
                    } else {
                        $cloudList = false;
                    }
                }

                $cloudList = true;
                while ($cloudList) {
                    $list = (new \app\service\TencentIM)->admin_getroammsg($result['touserid'], $result['userid'], 30);
                    if (isset($list['MsgList']) && sizeof($list['MsgList'])) {
                        (new \app\service\TencentIM)->delete_c2c_msg_ramble($result['touserid'], $result['userid'], array_column($list['MsgList'], 'MsgKey'));
                    } else {
                        $cloudList = false;
                    }
                }

                $request = request();
                $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getOtherList';
                $datas = json_encode(['userid' => $result['touserid']], JSON_UNESCAPED_UNICODE);
                sendcurl($url, $datas, 0);
                $datas = json_encode(['userid' => $result['userid']], JSON_UNESCAPED_UNICODE);
                sendcurl($url, $datas, 0);
                if($db){
                    foreach ($last as $key => $value) {
                        if ($value['type'] == 2) {
                            $hifile = Db::name('privatechat_greet')->where(['content'=>$value['content']])->find();
                            if (!$hifile) {
                                \app\service\AliOss::delete($value['content']);
                            }
                        } else if(in_array($value['type'], [1,3,4])){
                            \app\service\AliOss::delete($value['content']);
                        }
                    }

                    $users = Db::name('user')->where(['id'=>['in', [$result['userid'],$result['touserid']]]])->field('id,reg,authcode')->select();
                    foreach ($users as $uk => $uv) {
                        PrivatechatDeleTask::pushtask($uv['id'], $uv['reg'] == 2 ? $uv['authcode'] : $uv['id']);
                    }
                    $data=['ret'=>'删除成功'];
                }else{
                    $data=['err'=>'删除失败'];
                }
            }else{
                $data=['err'=>'id参数错误'];
            }
        }else{
            $data=['err'=>'提交参数错误'];
        }
        return $data;
    }

    // 批量删除
    public function delAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $list = Db::name('privatechat')->where('id', 'in', $post)->select();
                $ids = array_column($list, 'id');
                $insertArr = [];
                $userids = [];
                foreach ($list as $key => $value) {
                    $insertArr[] = ['userid'=>$value['userid'], 'touserid'=>$value['touserid'], 'msg_ids'=>$value['id'], 'create_time'=>time()];
                    $insertArr[] = ['userid'=>$value['touserid'], 'touserid'=>$value['userid'], 'msg_ids'=>$value['id'], 'create_time'=>time()];
                    $userids[] = $value['userid'];
                    $userids[] = $value['touserid'];
                    
                    if ($value['type'] == 2) {
                        $hifile = Db::name('privatechat_greet')->where(['content'=>$value['content']])->find();
                        if (!$hifile) {
                            \app\service\AliOss::delete($value['content']);
                        }
                    } else if(in_array($value['type'], [1,3,4])){
                        \app\service\AliOss::delete($value['content']);
                    }
                }
                $userids = array_unique($userids);
                $db = Db::name('privatechat')->where('id', 'in', $ids)->delete();
                Db::name('privatechat_dele_task')->insertAll($insertArr);
                foreach ($userids as $key => $value) {
                    PrivatechatDeleTask::pushtask($value);
                }


                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }



    public function delGroupAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $list = Db::name('privatechat')->where('id', 'in', $post)->select();
                $userids = array_column($list, 'userid');
                $touserids = array_column($list, 'touserid');
                $contents = array_column($list, 'content');
                $list = Db::name('privatechat')->where(['userid'=>['in',$userids], 'touserid'=>['in',$touserids], 'content'=>['in',$contents]])->select();
                $ids = array_column($list, 'id');
                $insertArr = [];
                $userids = [];
                foreach ($list as $key => $value) {
                    $insertArr[] = ['userid'=>$value['userid'], 'touserid'=>$value['touserid'], 'msg_ids'=>$value['id'], 'create_time'=>time()];
                    $insertArr[] = ['userid'=>$value['touserid'], 'touserid'=>$value['userid'], 'msg_ids'=>$value['id'], 'create_time'=>time()];
                    $userids[] = $value['userid'];
                    $userids[] = $value['touserid'];
                }
                $userids = array_unique($userids);
                $db = Db::name('privatechat')->where('id', 'in', $ids)->delete();
                Db::name('privatechat_dele_task')->insertAll($insertArr);
                foreach ($userids as $key => $value) {
                    PrivatechatDeleTask::pushtask($value);
                }


                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }















    public function rmchats()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $kfid = Db::name('config_system')->where(['title'=>'id'])->cache(60)->value('content');
        $type = input('type');
        switch(intval($type)){
            case 1:
                return $this->rmchatsquery("select id as msg_ids,userid,touserid,type,content from privatechat where type=-1 limit 20000");
                break;
            case 2:
                return $this->rmchatsquery("select id as msg_ids,userid,touserid,type,content FROM privatechat where type = 0 and finish = 1 and content <> '我在这儿呢' and userid <> $kfid and touserid <> $kfid and (userid,content) IN (SELECT userid,content FROM (SELECT userid,content FROM privatechat where type = 0 and content <> '我在这儿呢' GROUP BY userid,content HAVING COUNT(*)>3 ) s1) limit 20000");
                break;
            case 3:
                $soid = Db::query("select id from privatechat order by id desc limit 4000,1");
                if(sizeof($soid)){
                    return $this->rmchatsquery("select id as msg_ids,userid,touserid,type,content FROM privatechat where id < ".$soid[0]['id']." and finish = 1 and content <> '我在这儿呢' and (userid,touserid) IN (SELECT userid,touserid FROM (SELECT userid,touserid FROM privatechat where id < ".$soid[0]['id']." and content <> '我在这儿呢' GROUP BY userid,touserid HAVING COUNT(*)>1 ) s1) AND id NOT IN (SELECT id FROM (SELECT max(id) as id FROM privatechat where id < ".$soid[0]['id']." and content <> '我在这儿呢' GROUP BY userid,touserid HAVING COUNT(*)>1) s2) limit 20000");
                }else{
                    return json(['err'=>'暂未数据可清理']);
                }
                break;
            case 4:
                $soid = Db::table('privatechat')->whereTime('addtime', '<', '-7 days')->order('id','desc')->cache(3600)->value('id');
                if($soid){
                    return $this->rmchatsquery("select id as msg_ids,userid,touserid,type,content from privatechat where id < $soid limit 20000");
                }else{
                    return json(['err'=>'暂未数据可清理']);
                }
                break;
            case 5:
                $soid = Db::table('privatechat')->whereTime('addtime', '<', '-10 days')->order('id','desc')->value('id');
                if($soid){
                    $sql = "select id msg_ids,userid,touserid,type,content FROM privatechat WHERE id < $soid and id NOT IN (SELECT MAX(id) AS max_id FROM privatechat WHERE (userid, touserid) IN (SELECT userid, touserid FROM privatechat GROUP BY userid, touserid) GROUP BY userid, touserid)";
                    return $this->rmchatsquery2($sql);
                }else{
                    return json(['err'=>'暂未数据可清理']);
                }
                break;
        }
    }

    private function rmchatsquery($sql)
    {
        Cache::set('remove_wait', 1, 86400);
        $list = Db::query($sql);
        $time = time();
        $add = [];
        $files = [];
        if(sizeof($list)){
            $ids = array_column($list, 'msg_ids');
            foreach ($list as $key => $value) {
                // if(in_array($value['type'], [1,2,3,4])){
                //     $files[] = $value['content'][0] == '/' ? substr($value['content'], 1) : $value['content'];
                // }
                unset($value['type'], $value['content']);
                $value['create_time'] = $time;
                $add[] = $value;
                $userid = $value['touserid'];
                $value['touserid'] = $value['userid'];
                $value['userid'] = $userid;
                $add[] = $value;
            }
            // Db::name('privatechat_dele_task')->insertAll($add);
            $result = Db::execute("delete from privatechat where id in (" . implode(',',$ids) . ")");

            // \app\service\AliOss::deletes($files);
            
            $len = sizeof($ids);
            if($len > 5000){
                Cache::set('remove_wait', 1, 10);
            }else{
                Cache::rm('remove_wait');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait');
            return json(['err'=>'暂未数据可清理']);
        }
    }
    private function rmchatsquerybak($sql)
    {
        $delLimit = 20000;
        Cache::set('remove_wait', 1, 86400);
        $list = Db::query($sql);
        $time = time();
        $add = [];
        $files = [];
        if(sizeof($list)){
            $usergrouds = [];
            $ids = [];
            $cache_last_id = 0;
            foreach ($list as $key => $value) {
                if (!in_array($value['userid'].','.$value['touserid'], $usergrouds)) {
                    $usergrouds[] = $value['userid'].','.$value['touserid'];
                    $usergrouds[] = $value['touserid'].','.$value['userid'];
                    continue;
                }
                $ids[] = $value['msg_ids'];
                // if(in_array($value['type'], [1,2,3,4])){
                //     $files[] = $value['content'][0] == '/' ? substr($value['content'], 1) : $value['content'];
                // }
                unset($value['type'], $value['content']);
                $value['create_time'] = $time;
                $add[] = $value;
                $userid = $value['touserid'];
                $value['touserid'] = $value['userid'];
                $value['userid'] = $userid;
                $add[] = $value;
                if (sizeof($ids) >= $delLimit) {
                    break;
                }
            }
            
            $idslen = sizeof($ids);
            if ($idslen == 0) {
                Cache::rm('remove_wait');
                return json(['err'=>'暂无数据可清理']);
            }
            Db::name('privatechat_dele_task')->insertAll($add);
            $result = Db::execute("delete from privatechat where id in (" . implode(',',$ids) . ") limit $delLimit");

            // \app\service\AliOss::deletes($files);
            
            if($idslen > 5000){
                Cache::set('remove_wait', 1, 10);
            }else{
                Cache::store('redis')->set('rmchatsquerylastid', $ids[0], 86400);
                Cache::rm('remove_wait');
            }
            return json(['ret'=>'已清理' . $idslen . '条。原始sql：' . $sql]);
        }else{
            Cache::rm('remove_wait');
            return json(['err'=>'暂无数据可清理']);
        }
    }
    private function rmchatsquery2($sql)
    {
        $delLimit = 20000;
        Cache::set('remove_wait', 1, 86400);
        $list = Db::query($sql);
        $time = time();
        $add = [];
        if(sizeof($list)){
            $ids = [];
            foreach ($list as $key => $value) {
                $ids[] = $value['msg_ids'];
                unset($value['type'], $value['content']);
                $value['create_time'] = $time;
                $add[] = $value;
                $userid = $value['touserid'];
                $value['touserid'] = $value['userid'];
                $value['userid'] = $userid;
                $add[] = $value;
                if (sizeof($ids) >= $delLimit) {
                    break;
                }
            }
            
            $idslen = sizeof($ids);
            if ($idslen == 0) {
                Cache::rm('remove_wait');
                return json(['err'=>'暂无数据可清理']);
            }
            Db::name('privatechat_dele_task')->insertAll($add);
            $result = Db::execute("delete from privatechat where id in (" . implode(',',$ids) . ") limit $delLimit");

            
            if($idslen > 5000){
                Cache::set('remove_wait', 1, 10);
            }else{
                Cache::rm('remove_wait');
            }
            return json(['ret'=>'已清理' . $idslen . '条。原始sql：' . $sql]);
        }else{
            Cache::rm('remove_wait');
            return json(['err'=>'暂无数据可清理']);
        }
    }


    public function rmdeletask()
    {
        if(Cache::get('remove_wait')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $list = PrivatechatDeleTask::where(['state'=>1])->master()->count();
        $del = PrivatechatDeleTask::where(['state'=>1])->limit(20000)->delete();
        if($del > 5000){
            Cache::set('remove_wait', 1, 10);
        }else{
            Cache::rm('remove_wait');
        }
        return json(['ret'=>'已清理' . $del . '条，还剩余' . ($list - $del) . '条']);
    }




    // 聊天费用折扣
    public function limitChatPrice()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if(in_array($search_type, ['id', 'phone'])){
                $where['t2.'.$search_type . '|t3.'.$search_type] = $search_name;
            }elseif(in_array($search_type, ['name'])){
                $where['t2.'.$search_type . '|t3.'.$search_type] = ['like', '%'.$search_name.'%'];
            }else{
                $where['t1.'.$search_type] = ['like', '%'.$search_name.'%'];
            }
        }

        $start = input('start');
        $end = input('end');

        if ($start && $end) {
            $where['t1.update_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.update_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.update_time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $data = Db::name('limit_chat_price')
                    ->alias('t1')
                    ->join('user t2','t1.user_id=t2.id')
                    ->join('user t3','t1.another_id=t3.id')
                    ->where($where)
                    ->field('t1.*,t2.name uaname,t3.name ubname')
                    ->order('t1.update_time desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function limitChatPriceAdd()
    {
        $post = input('post.');

        $user = Db::name('user')->find($post['user_id']);
        $another = Db::name('user')->find($post['another_id']);

        $time = time();
        $result = ['state' => 0, 'msg' => '操作失败'];
        if ($user && $another) {
            if ($post['user_id'] > $post['another_id']) {
                $map = ['user_id'=>$post['another_id'], 'another_id'=>$post['user_id']];
            } else {
                $map = ['another_id'=>$post['another_id'], 'user_id'=>$post['user_id']];
            }
            if(!$post['scale'] || $post['scale'] > 99 || $post['scale'] < 1){
                return ['state' => 0, 'msg' => '折扣错误值'];
            }
            $limitchatprice = Db::name('limit_chat_price')->where($map)->find();
            if($limitchatprice){
                $res = Db::name('limit_chat_price')->where(['id'=>$limitchatprice['id']])->update(['scale'=>$post['scale'], 'update_time'=>$time]);
            }else{
                $map['scale'] = $post['scale'];
                $map['create_time'] = $map['update_time'] = $time;
                $res = Db::name('limit_chat_price')->insertGetid($map);
            }
            if ($res) {
                $result = ['state' => 1, 'msg' => '操作成功'];
            }
        }
        return $result;
    }

    public function limitChatPriceDele()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            Db::name('limit_chat_price')->where('user_id', $id)->delete();
            $data = ['state' => 1, 'msg' => '设置成功'];
        }
        return $data;
    }

    public function limitChatPriceScale($id, $data)
    {
        $id = input('id');
        $data = input('data/d', 0);
        if(!$data || $data > 99 || $data < 1){
            return ['err'=>'错误值'];
        }
        $res = Db::name('limit_chat_price')->where(['id'=>$id])->update(['scale'=>$data]);
        if($res){
            $data = ['ret' => '修改成功'];
        }else{
            $data = ['err' => '修改失败'];
        }
        return $data;
    }

    public function intimate()
    {
        $where = [];
        $search_name=input('param.name');
        $search_type=input('param.search');

        if($search_name && $search_type !== null){
            if ($search_type == 'userid') {
                if (stripos($search_name, ',')) {
                    $search_name = explode(',', $search_name);
                    $where['couple_a'] = $search_name[0] < $search_name[1] ? $search_name[0].','.$search_name[1] : $search_name[1].','.$search_name[0];
                } else {
                    $where  = 'find_in_set("'.$search_name.'",couple_a)';
                }
            }
        }
        $data=DB::name('user_intimate')
                ->where($where)
                ->order('intimate desc')
                ->paginate(_getCachePages(),false,['query'=>request()->param()])
                ->each(function($item, $key){
                    $userid = explode(',', $item['couple_a']);
                    $item['userid'] = $userid[0];
                    $item['touserid'] = $userid[1];
                    return $item;
                });
        $this->assign('data',$data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }
    public function systemPushVideoRecords()
    {
        $where = [];
        $search_name=input('param.name');
        $search_type=input('param.search');

        if($search_name && $search_type !== null){
            $where[$search_type] = $search_name;
        }
        $data=DB::name('push_lianmai_system')
                ->where($where)
                ->order('id desc')
                ->paginate(_getCachePages(),false,['query'=>request()->param()])
                ->each(function($item, $key){
                    return $item;
                });
        $this->assign('data',$data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }


    public function words()
    {
        $kefu = Db::name('config_system')->where(['category'=>'kefu','title'=>'id'])->value('content');
        $where = ['user_id' => ['<>',$kefu]];
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $channel = input('channel');
        if ($channel) {
            $where['channel'] = $channel;
        }
		//添加审核分类功能
		$shenhe = input('shenhe');
		$this->assign('shenhe',$shenhe);
		//dump($shenhe);
		if(isset($shenhe)){
		    if($shenhe==1){//通过
		        $where['shenhe_state'] = 1;
		    }elseif($shenhe==0){//待审核
		        $where['shenhe_state'] = 0;
		    }elseif($shenhe==-1){//拒绝
		        $where['shenhe_state'] = -1;
		    }
		}

        $data = Db::name('privatechat_default')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('channel', $channel);

        return $this->fetch();
    }

    public function delWords()
    {
        if (request()->isAjax()) {
            $id = input('id');
            $word = Db::name('privatechat_default')->find($id);
            if ($word) {
                $db = Db::name('privatechat_default')->delete($id);
                if ($db) {
                    Cache::rm("word&2&". $word['user_id']);
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function delAllWords()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $list = Db::name('privatechat_default')->where('id', 'in', $post)->select();
                $ids = array_column($list, 'id');
                $user_ids = array_column($list, 'user_id');
                $db = Db::name('privatechat_default')->where('id', 'in', $ids)->delete();
                if ($db) {
                    foreach ($user_ids as $key => $value) {
                        Cache::rm("word&2&". $value);
                    }
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => '删除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    public function orderInfo($id)
    {
        $order = Db::name('order_common')->find($id);
        $data = json_decode($order['data'], true);
        return ['state'=>1, 'data'=>$data];
    }


    public function liaoyou()
    {
        $name = input('name', '');
        $where = 'unshow=0';
        if ($name) {
            if (strpos($name, ',') !== false) {
                $where .= " and (couple_a='$name' or couple_b='$name')";
            } else {
                $where .= ' and find_in_set('.$name.', couple_a)';
            }
        }
        $data=DB::name('user_intimate')->master()->where($where)->order('update_time desc,id desc')->paginate(_getCachePages(),false,['query'=>request()->param()])->each(function($item, $key){
            $user = explode(',', $item['couple_a']);
            $item['user_a'] = $user[0];
            $item['user_b'] = $user[1];
            return $item;
        });
        $this->assign('data',$data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }



    public function liaoyouUpdate()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $user_intimates = Db::name('user_intimate')->where('id', 'in', $post)->select();
                $db = Db::name('user_intimate')->where('id', 'in', $post)->update(['unshow'=>1]);
                if ($db) {
                    foreach ($user_intimates as $key => $value) {
                        $users = explode(',', $value['couple_a']);
                        Db::name('chat_lists')->where(['user_id'=>$users[0], 'another_id'=>$users[1]])->update(['user_first'=>1,'another_first'=>1]);
                    }
                    $data = ['ret' => '解除成功'];
                } else {
                    $data = ['err' => '解除失败'];
                }
            } else if (input('?post.id')) {
                $user_intimate = Db::name('user_intimate')->where('id', '=', input('id'))->find();
                $db = Db::name('user_intimate')->where('id', '=', input('id'))->update(['unshow'=>1]);
                if ($db) {
                    $users = explode(',', $user_intimate['couple_a']);
                    Db::name('chat_lists')->where(['user_id'=>$users[0], 'another_id'=>$users[1]])->update(['user_first'=>1,'another_first'=>1]);
                    $data = ['ret' => '解除成功'];
                } else {
                    $data = ['err' => '解除失败'];
                }
            } else {
                $data = ['err' => '解除失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }



    public function banWord()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('ban_word')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    //添加标签
    public function addBanWord()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                $record_id = Db::name('ban_word')->where(['name' => $post['name']])->value('id');
                if ($record_id) return ['err' => '违禁词已存在'];

                $res = db('ban_word')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $res = db('ban_word')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('ban_word')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除标签
    public function delBanWord()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('ban_word')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function ChatWarnWechatUser()
    {
        $where = ['status'=>1];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('chat_warn_wechat_user')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addChatWarnWechatUser()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                $record_id = Db::name('chat_warn_wechat_user')->where(['user_id' => $post['user_id'], 'status'=>1])->value('id');
                if ($record_id) return ['err' => '已存在'];
                $user = _user_cache($post['user_id']);
                if (!$user) return ['err' => '用户不存在'];
                $post['create_time'] = time();
                $post['status'] = 1;
                $res = db('chat_warn_wechat_user')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $post['update_time'] = time();
                $res = db('chat_warn_wechat_user')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('chat_warn_wechat_user')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delChatWarnWechatUser()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('chat_warn_wechat_user')->where('id',$pid)->update(['status'=>0]);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    public function ChatWarnWechatContent()
    {
        $where = ['delete_time'=>0];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('chat_warn_wechat_content')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addChatWarnWechatContent()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                $record_id = Db::name('chat_warn_wechat_content')->where(['content' => $post['content'], 'delete_time'=>0])->value('id');
                if ($record_id) return ['err' => '已存在'];

                $post['create_time'] = time();
                $res = db('chat_warn_wechat_content')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $res = db('chat_warn_wechat_content')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('chat_warn_wechat_content')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delChatWarnWechatContent()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('chat_warn_wechat_content')->where('id',$pid)->update(['delete_time'=>time()]);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function ChatWarnWechatRecords()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = db('chat_warn_wechat_records')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }



    public function LianmaiLimit()
    {
        $where = ['banned_time'=>['>', time()]];
        $state = input('state/d', 0);
        if ($state) {
            $where = ['banned_time'=>['<=', time()]];
        }
        $this->assign('state', $state);


        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            if ($search_type == 'user_id') {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = db('privatechat_lianmai_limit')->master()->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addLianmaiLimit()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                $record_id = Db::name('privatechat_lianmai_limit')->master()->where(['user_id' => $post['user_id'], 'banned_time'=>['>', time()]])->value('id');
                if ($record_id) return ['err' => '当前用户已被限制'];

                $post['banned_time'] = strtotime($post['banned_time']);
                $post['create_time'] = time();
                $res = db('privatechat_lianmai_limit')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $res = db('privatechat_lianmai_limit')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = db('privatechat_lianmai_limit')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delLianmaiLimit()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('privatechat_lianmai_limit')->where('id',$pid)->update(['banned_time'=>time()]);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function pornoRecords()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = $search_name;
        }

        $data = db('privatechat_lianmai_porno')
                    ->master()
                    ->where($where)
                    ->order('id desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()])
                    ->each(function($item){
                        $banned = Db::name('privatechat_lianmai_limit_single')->where("(user_id=".$item['user_id']." and touser_id=".$item['touser_id'].") or (user_id=".$item['touser_id']." and touser_id=".$item['user_id'].")")->where(['banned_time'=>['>', time()]])->find();

                        $item['banned_id'] = '';
                        $item['banned_time'] = '';
                        if ($banned) {
                            $item['banned_id'] = $banned['id'];
                            $item['banned_time'] = $banned['banned_time']?date('Y-m-d H:i:s', $banned['banned_time']):'';
                        }

                        $couple = $item['user_id'] < $item['touser_id'] ? $item['user_id'].','.$item['touser_id'] : $item['touser_id'].','.$item['user_id'];
                        $item['intimate'] = Db::name('user_intimate')->where(['couple_a'=>$couple])->cache('intimate:'. $couple)->value('intimate');
                        return $item;
                    });
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }


    public function LianmaiLimitSingle()
    {
        $where = ['banned_time'=>['>', time()]];
        $state = input('state/d', 0);
        if ($state) {
            $where = ['banned_time'=>['<=', time()]];
        }
        $this->assign('state', $state);

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            if ($search_type=='user_id') {
                $where['user_id|touser_id'] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = db('privatechat_lianmai_limit_single')->master()->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addLianmaiLimitSingle()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) { //添加数据
                $record_id = Db::name('privatechat_lianmai_limit_single')->master()->where(['user_id' => $post['user_id'], 'touser_id' => $post['touser_id'], 'type' => $post['type'], 'banned_time'=>['>', time()]])->value('id');
                if ($record_id) return ['err' => '当前用户已被限制'];

                $post['banned_time'] = strtotime($post['banned_time']);
                $post['create_time'] = time();
                $res = db('privatechat_lianmai_limit_single')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else { //修改数据
                $res = db('privatechat_lianmai_limit_single')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            $user_id = input('user_id', '');
            $touser_id = input('touser_id', '');
            if ($id) {
                $name = db('privatechat_lianmai_limit_single')->master()->where('id', $id)->find();

                if ($name) {
                    $name['banned_time'] = date('Y-m-d H:i:s', $name['banned_time']);
                    $this->assign('id', $id);
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            } else if ($user_id) {
                $this->assign('id', '');
                $this->assign('user_id', $user_id);
                $this->assign('touser_id', $touser_id);
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function delLianmaiLimitSingle()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = db('privatechat_lianmai_limit_single')->where('id',$pid)->update(['banned_time'=>time()]);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }




    public function initchatlist()
    {
        $name = input('name', '');
        $data = [];
        IF ($name) {
            $user = Db::name('user')->find($name);
            if ($user) {
                $kefu = Db::name('config_system')->where(['category'=>'kefu','title'=>'id'])->value('content');
                $user_intimate = DB::name('user_intimate')->master()->where("find_in_set('$name', couple_a)")->column('couple_a');
                $user_intimate_touser = [$kefu];
                foreach ($user_intimate as $key => $value) {
                    $uids = explode(',', $value);
                    $user_intimate_touser[] = $uids[0] == $name ? $uids[1] : $uids[0];
                }
                $selfpush = Db::name('chat_lists')->where(['user_id'=>$name, 'another_id'=>['not in', $user_intimate_touser]])->select();
                $selfpull = Db::name('chat_lists')->where(['another_id'=>$name, 'user_id'=>['not in', $user_intimate_touser]])->select();
                $allchatlist = array_merge($selfpush, $selfpull);
                $alluser = Db::name('user')->where(['id'=>['in', array_merge(array_column($allchatlist, 'user_id'), array_column($allchatlist, 'another_id'))]])->column('name,sex', 'id');
                foreach ($allchatlist as $key => $value) {
                    if (!isset($alluser[$value['user_id']]) || !isset($alluser[$value['another_id']])) {
                        continue;
                    }
                    if ($alluser[$value['user_id']]['sex'] == '女' && !$value['user_first']) {
                        $data[] = $value;
                        continue;
                    }
                    if ($alluser[$value['another_id']]['sex'] == '女' && !$value['another_first']) {
                        $data[] = $value;
                    }
                }
            }
        }
        $this->assign('data',$data);
        return $this->fetch();
    }



    public function initChat()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('chat_lists')->where(['id'=>['in', $post]])->update(['user_first'=>1,'another_first'=>1]);
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else if (input('?post.id')) {
                $db = Db::name('chat_lists')->where(['id'=>input('post.id')])->update(['user_first'=>1,'another_first'=>1]);
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    public function record_audio()
    {
        $where = ['type'=>2];

        $whereor = ['type'=>2];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $start = input('start');
        $end = input('end');

        if ($search_name && $search_type) {
            if (stripos($search_name, ',') && $search_type == 'userid') {
                $search_name = explode(',', $search_name);
                $where['userid']  = $search_name[0];
                $where['touserid']  = $search_name[1];
                $whereor['touserid']  = $search_name[0];
                $whereor['userid']  = $search_name[1];
            } else if (in_array($search_type, ['userid', 'touserid'])) {
                $where[$search_type] = $search_name;
                $whereor[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
                $whereor[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }


        if ($start && $end) {
            $where['addtime'] = $whereor['addtime'] = ['between', [$start, $end]];
            $start_id = _day_first_id($start);
            $end_id = _day_first_id(date('Y-m-d', strtotime($start))==date('Y-m-d', strtotime($end))?date('Y-m-d', strtotime($end)+86400):$end, $start_id);
            if ($end_id) {
                $where['id'] = $whereor['id'] = ['between', [$start_id, $end_id]];
            }
        } else if ($start && !$end) {
            if (time() - strtotime($start) > 6 * 60*60*24*30) {
                $start = date('Y-m-d') . ' 00:00:00';
            }
            $where['addtime'] = $whereor['addtime'] = ['egt', $start];
            $start_id = _day_first_id($start);
            if ($start_id) {
                $where['id'] = $whereor['id'] = ['egt', $start_id];
            }
        } else if (!$start && $end) {
            $where['addtime'] = $whereor['addtime'] = ['elt', $end];
            $end_id = _day_first_id($end);
            if ($end_id) {
                $where['id'] = $whereor['id'] = ['egt', $end_id];
            }
        }

        $data = db('privatechat')->master()->where($where)->whereOr(function ($query) use ($whereor) {
                    $query->where($whereor);
                })->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function tostring($url = '')
    {
        try {
            $result = BaiduApi::Asr($url);
        } catch (\Exception $e) {
            return ['err'=>'识别失败'];
        }
        if($result){
            return ['ret'=>$result];
        }else{
            return ['err'=>'识别失败'];
        }
    }



    public function shenheWords()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $word = Db::name('privatechat_default')->find($id);
                
                $db = Db::name('privatechat_default')->where('id', $id)->update(['shenhe_state' => $post['status'], 'shenhe_time'=>time(), 'shenhe_admin_id'=>$this->adminInfo['id']]);
                
                Cache::rm('word&1&' . $word['user_id']);
                Cache::rm('word&2&' . $word['user_id']);
                
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }
	
	 //批量通过未审核的数据
	public function plPass()
	{
		if (request()->isAjax()) {
			$post = input('post.');
			if (input('?post.delAll')) {
				$post = $post['delAll'];
				$list = Db::name('privatechat_default')->where('id', 'in', $post)->select();
				$ids = array_column($list, 'id');//从结果数组中取出id列生成新数组
				$user_ids = array_column($list, 'user_id');//从结果数组中取出user_id列生成新数组
				$db = Db::name('privatechat_default')->where('id', 'in', $ids)->where('shenhe_state',0)->update(['shenhe_state'=>1]);
				if ($db) {
					$data = ['ret' => '通过成功'];
				} else {
					$data = ['err' => '通过失败'];
				}
			} else {
				$data = ['err' => '通过失败，未选中数据'];
			}
		} else {
			$data = ['err' => '提交类型错误'];
		}
		return $data;
	}
}